using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;


namespace RovNetMonService
{
    public partial class RovNetMonService : ServiceBase
    {
       /* [DllImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceExA")]
        private static extern long GetDiskFreeSpaceEx(string lpDirectoryName,
          out long lpFreeBytesAvailableToCaller,
          out long lpTotalNumberOfBytes,
          out long lpTotalNumberOfFreeBytes);*/

     /*   internal long _GetFreeDiskSpace(string driveName)
        {
            long totalBytes, freeBytes, freeBytesAvail, result;

            if (!Directory.Exists(driveName))
                throw new ArgumentException("Invalid Drive " + driveName);

            result = GetDiskFreeSpaceEx(driveName,
                out freeBytesAvail,
                out totalBytes,
                out freeBytes);

            return freeBytesAvail;

        }*/


        protected PerformanceCounter cpuCounter;
        protected PerformanceCounter ramCounter;
        Thread thread;
        TcpListener listener;
        bool running = false;

        public RovNetMonService()
        {
            cpuCounter = new PerformanceCounter();

            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 
           
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            running = true;
            thread = new Thread(new ThreadStart(go));
            thread.Start();
        }


        protected void go()
        {
            while (running)
            {
                try
                {
                    byte[] data = new byte[512];
                    string s = "";
                    listener = new TcpListener(new IPEndPoint(IPAddress.Any, 9000));
                    listener.Start();

                    while (running)
                    {
                        System.Text.Encoding enc = System.Text.Encoding.ASCII;
                        Socket socket = listener.AcceptSocket();

                        if (socket.Connected)
                        {
                            socket.Receive(data, SocketFlags.None);
                            s = enc.GetString(data);
                            int value = -9;
                            if (s.StartsWith("CPU"))
                                value = (int)cpuCounter.NextValue();

                            if (s.StartsWith("MEM"))
                                value = (int)ramCounter.NextValue();

                            if (s.StartsWith("FS"))
                            {
                                DriveInfo di = new DriveInfo(s.Substring(2, 1));
                                value = (int)(di.AvailableFreeSpace * 100 / di.TotalSize);
                            }

                            Byte[] dataOut = System.Text.Encoding.ASCII.GetBytes(value.ToString());
                            socket.Send(dataOut, SocketFlags.None);

                            socket.Shutdown(SocketShutdown.Both);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                listener.Stop();

                Thread.Sleep(5000);
            }
        }

        protected override void OnStop()
        {
            running = false;
            thread.Abort();
            Thread.Sleep(1000);
            listener.Stop();
        }

        protected void Send(String server, String message, Int32 port)
        {
            try
            {
                TcpClient client = new TcpClient(server, port);

                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }

      
    }
}
